import requests
from bs4 import BeautifulSoup
import tkinter as tk
from tkinter import messagebox

# 全局变量用于存储当前价格和爬取次数
current_price = None
fetch_count = 0
endFlag = False
title = ""

def fetch_price(url):
    global current_price, fetch_count
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
    response = requests.get(url, headers=headers)
    fetch_count += 1  # 每次请求增加计数器
    soup = BeautifulSoup(response.text, 'html.parser')
    price_span =  soup.find(class_=lambda x: x and x.startswith("font-bold index_price__Y5U5k"))
   

    # font-bold index_price__Y5U5k font-24
    if price_span:
        price_str = price_span.text.strip().replace(',', '').replace('$', '')  # 去除货币符号和逗号
        price = float(price_str)
        current_price = price
        return price
    else:
        return None

def calculate_difference(principal, principal1):
    global current_price
    if current_price is not None:
        difference = (current_price * principal) - (principal1 * principal)
        return difference
    else:
        return None

def check_price():
    global title, current_price
    principal = float(principal_entry.get())  # 个数
    principal1 = float(principal_entry1.get())  # 买入价位
    url = url_entry.get().strip()
    title = title_entry.get().strip()
    if not title:
        title = "pixi"
    if not url:
        url = "https://www.obvffnzyxaqa.com/zh-hans/web3/dex-market/detail/501/FtHCi9cxJSSizrzMzsPjAfTfJi32V1CGRDM5Skqn4QBF"
    price = fetch_price(url)
    if price is not None:
        price_label.config(text=f"当前价格: {price}, 本次监测次数: {fetch_count}")  # 显示爬取次数
        difference = calculate_difference(principal, principal1)
        if difference is not None:
            difference_label.config(text=f"差额: {difference}")
            if price > float(max_value_entry.get()):
                messagebox.showinfo("Alert", f"{title}当前价格 {price} 大于最大值 {max_value_entry.get()}！")
                stop_monitor()
            elif price < float(min_value_entry.get()):
                messagebox.showinfo("Alert", f"{title}当前价格 {price} 小于最小值 {min_value_entry.get()}！")
                stop_monitor()
    if endFlag:
        root.after(3000, check_price)  # 3秒后再次执行 check_price

def stop_monitor():
    global endFlag ,fetch_count
    endFlag = False
    fetch_count = 0
    # price_label.config(text=f"当前价格: -, 本次监测次数: -") 
    messagebox.showinfo("Info", "停止监测！")

def start_monitor():
    global endFlag 
    endFlag = True    
    check_price()

def show_help():
    help_text = """这是一个监测价格的小工具。
    - 输入网址，设置监测的最大值和最小值。
    - 在“买入点位”输入框中输入买入价位，以及“本金(个数)”输入框中输入个数。
    - 点击“开始监测”按钮开始监测价格，点击“停止监测”按钮停止监测。
    - 最近改动:
            停止监测时,本次监测次数清空
            新增可输入同域名下其它网址, 为空时默认爬取pixi
    - 你也可以点击此按钮来查看帮助信息。
    - 有其它疑问联系'大肌霸'邮箱 888@gmail.com"""
    messagebox.showinfo("帮助", help_text)

# 创建主窗口
root = tk.Tk()
root.title("crawl")

# URL输入框
url_label = tk.Label(root, text="网址(默认pixi):")
url_label.grid(row=0, column=0)
url_entry = tk.Entry(root)
url_entry.grid(row=0, column=1)

# 标题输入框
title_label = tk.Label(root, text="标题(默认pixi):")
title_label.grid(row=1, column=0)
title_entry = tk.Entry(root)
title_entry.grid(row=1, column=1)

# 最大值输入框
max_value_label = tk.Label(root, text="最大值:")
max_value_label.grid(row=2, column=0)
max_value_entry = tk.Entry(root)
max_value_entry.grid(row=2, column=1)

# 最小值输入框
min_value_label = tk.Label(root, text="最小值:")
min_value_label.grid(row=3, column=0)
min_value_entry = tk.Entry(root)
min_value_entry.grid(row=3, column=1)

# 买入价位输入框
principal_label1 = tk.Label(root, text="买入点位:")
principal_label1.grid(row=4, column=0)
principal_entry1 = tk.Entry(root)
principal_entry1.grid(row=4, column=1)

# 本金输入框
principal_label = tk.Label(root, text="本金(个数):")
principal_label.grid(row=5, column=0)
principal_entry = tk.Entry(root)
principal_entry.grid(row=5, column=1)

# 当前价格显示标签
price_label = tk.Label(root, text="")
price_label.grid(row=6, column=0, columnspan=2)

# 差额显示标签
difference_label = tk.Label(root, text="")
difference_label.grid(row=7, column=0, columnspan=2)

# 按钮
start_button = tk.Button(root, text="开始监测", command=start_monitor)
start_button.grid(row=8, column=0)

stop_button = tk.Button(root, text="停止监测", command=stop_monitor)
stop_button.grid(row=8, column=1)

help_button = tk.Button(root, text="?", command=show_help)
help_button.grid(row=0, column=2)

root.mainloop()
